/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-30 15:33:40   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zx.cloud.domain.Dict;
import com.zx.cloud.domain.LoanOrder;
import com.zx.cloud.domain.OrderLog;
import com.zx.cloud.domain.RepayOrder;
import com.zx.cloud.domain.User;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.DictMapper;
import com.zx.cloud.persistence.LoanOrderMapper;
import com.zx.cloud.persistence.OrderLogMapper;
import com.zx.cloud.persistence.RepayOrderMapper;
import com.zx.cloud.persistence.UserMapper;
import com.zx.cloud.util.Page;

/**
 * 借款订单表
 */
@SpringBootApplication
@Transactional
@Service
public class LoanOrderService extends CrudServiceImpl<LoanOrder> {
	static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	private static final Logger LOGGER = LoggerFactory
			.getLogger(LoanOrderService.class);

	@Autowired
	private LoanOrderMapper loanOrderMapper;
	@Autowired
	private RepayOrderMapper repayOrderMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private OrderLogMapper orderLogMapper;
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private DictMapper dictMapper;
	
	@Value("${spring.profiles.active}")
	private String active;
	
	@Autowired
	public LoanOrderService(CrudMapper<LoanOrder> mapper) {
		super(mapper);
	}
	/**
	 * @Description:借款管理-借款订单列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	@Override
	public Page<LoanOrder> page(LoanOrder entity) {
		long count = loanOrderMapper.getLoanOrderCount(entity);
		Page<LoanOrder> page = new Page<LoanOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(loanOrderMapper.getLoanOrderList(entity));
		page.setTotalCount(count);
		return page;
	}
	/**
	 * @Description:我(会员)的借款订单
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public List<LoanOrder> getLoanOrderByClientId(Map<String, Object> params){
		
		return  loanOrderMapper.getLoanOrderByClientId(params);
	}
	/**
	 * @Description:借款管理-创建借款订单
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	@Override
	public int insert(LoanOrder entity) {
		LoanOrder  newLoanOrder=new LoanOrder();
		//根据会员，选择正常利息利率0.0005、征信服务费利率0.0095、逾期利率0.015,后期维护到会员的映射关系中
		Long clientId=entity.getClientId();
		newLoanOrder.setClientId(clientId);
		BigDecimal interestRate=new BigDecimal(0);
		BigDecimal serviceRate=new BigDecimal(0);
		BigDecimal overdueRate=new BigDecimal(0);
		 Dict dict=new Dict();
		 dict.setParentCode("R0001");
		 List<Dict> dicts=dictMapper.getDitByParentCode(dict);
		 for (int i = 0; i < dicts.size(); i++) {
			if("R00001".equals(dicts.get(i).getCode())){
				interestRate=interestRate.add(new BigDecimal(dicts.get(i).getValue()));
			}
			if("R00002".equals(dicts.get(i).getCode())){
				serviceRate=serviceRate.add(new BigDecimal(dicts.get(i).getValue()));
			}
			if("R00003".equals(dicts.get(i).getCode())){
				overdueRate=overdueRate.add(new BigDecimal(dicts.get(i).getValue()));
			}
		}
		newLoanOrder.setInterestRate(interestRate);
		newLoanOrder.setServiceRate(serviceRate);
		newLoanOrder.setOverdueRate(overdueRate);
		
		BigDecimal loanAmount=entity.getLoanAmount();
		newLoanOrder.setLoanAmount(loanAmount);//借款金额
		//正常利息
        BigDecimal  repayInterest=loanAmount.multiply( interestRate ).multiply( new BigDecimal(entity.getLoanTerm() ) );
        newLoanOrder.setRepayInterest(repayInterest);
		//征信服务费
		BigDecimal serviceCharge=loanAmount.multiply( serviceRate ).multiply( new BigDecimal(entity.getLoanTerm() ) );
		newLoanOrder.setServiceCharge(serviceCharge);
		//借款期限低于10天,额外利息
		BigDecimal addInterest=new BigDecimal(0);
		newLoanOrder.setLoanTerm(entity.getLoanTerm());
		if(10 >= entity.getLoanTerm() ){
			addInterest=addInterest.add(new BigDecimal(30));
			newLoanOrder.setAddInterest(addInterest);
		}
		BigDecimal feeTotal=repayInterest.add(serviceCharge).add(addInterest);
		newLoanOrder.setFeeTotal(feeTotal);//贷款服务费总和
		newLoanOrder.setActualAmount(loanAmount.subtract(feeTotal));//到账金额
		newLoanOrder.setOrderNo(simpleDateFormat.format(new Date())+getRandomByCount(3));//订单编号
		newLoanOrder.setLivingPic(entity.getLivingPic());//活体识别
		newLoanOrder.setCreateTime(OffsetDateTime.now());//创建时间
		newLoanOrder.setStatus(0);//初始状态		
		return mapper.insert(newLoanOrder);
	}
	/**
	 * @Description:借款管理-借款订单列表-审核
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public int checkLoanOrder(LoanOrder loanOrder, Long userId) {
		/**更新借款订单*/
		LoanOrder  newLoanOrder=new LoanOrder();
		newLoanOrder.setId(loanOrder.getId());
		newLoanOrder.setStatus(loanOrder.getStatus());
		super.update(newLoanOrder);
		
		/**订单操作日志*/
		if (1==loanOrder.getStatus()) {
			orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"审核拒绝");
		} else if (2==loanOrder.getStatus()) {
			orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"审核通过");
		}
		return 1;
	}
	
	private  String getRandomByCount(int count) {
		String resStr = "";
		for (int i = 0; i < count; i++) {
			resStr += (int) (10 * (Math.random()));
		}
		return resStr;
	}
	/**
	 * @Description:借款管理-放款订单列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public Page<LoanOrder> pageLendingOrder(LoanOrder entity) {
		LOGGER.info("==============放款订单列表===============");
		if(!"prod".equals(active)){
			LOGGER.info("==============非生产环境1分钱测试"+"spring.profiles.active："+active+"============");
		 }else {
			 LOGGER.info("==============生产环境==============");
		 }
		long count = loanOrderMapper.getLendingOrderCount(entity);
		Page<LoanOrder> page = new Page<LoanOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(loanOrderMapper.getLendingOrderList(entity));
		page.setTotalCount(count);
		return page;
	}
	
	/**
	 * @Description:借款管理-放款订单列表-放款
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public int doLending(LoanOrder loanOrder, Long userId) {
		LOGGER.info("==============放款===============");
		if(!"prod".equals(active)){
			LOGGER.info("==============非生产环境1分钱测试"+"spring.profiles.active："+active+"============");
		 }else {
			 LOGGER.info("==============生产环境=============");
		 }
		Long orderId=loanOrder.getId();
		LoanOrder loanOrderData=super.get(orderId);
		/**放款*/
		Long clientId=loanOrderData.getClientId();
		/*********************支付通道************************/
		/**修改借款订单*/
		LoanOrder  newLoanOrder=new LoanOrder();
		newLoanOrder.setId(loanOrder.getId());
		newLoanOrder.setStatus(3);//已放款
		//放款时间
		OffsetDateTime  loanTime=OffsetDateTime.now();
		newLoanOrder.setLoanTime(loanTime);
		//借款期限
		Integer loanTerm=loanOrderData.getLoanTerm();
		//到期时间
		OffsetDateTime  expirationTime=loanTime.plusDays(loanTerm.longValue());
		newLoanOrder.setExpirationTime(expirationTime);
		super.update(newLoanOrder);
		/**生成还款订单*/
		RepayOrder repayOrder=new RepayOrder();
		repayOrder.setLoanOrderId(orderId);
		repayOrder.setRepayAmount(loanOrderData.getLoanAmount());
		repayOrder.setOverdueRate(loanOrderData.getOverdueRate());//逾期利率
		repayOrder.setIsOverdue(0);//初始化：未逾期
		repayOrder.setStatus(0);//初始化：未还款
		repayOrder.setCreateTime(OffsetDateTime.now());//创建时间
		repayOrder.setBorrowTime(loanOrderData.getCreateTime());//借款时间
		repayOrder.setExpirationTime(expirationTime);//到期时间
		repayOrderMapper.insert(repayOrder);
		/**订单操作日志*/
		orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"放款");
		return 1;
	}
	/**
	 * @Description:借款管理-放款订单列表-放款回调
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public int doLendingCallBack(OffsetDateTime  time) {
		return 1;
	}
	/**
	 * @Description:我的借款订单列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public Page<LoanOrder> pageMyLoanOrder(LoanOrder entity) {
		long count = loanOrderMapper.getMyLoanOrderCount(entity);
		Page<LoanOrder> page = new Page<LoanOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(loanOrderMapper.getMyLoanOrderList(entity));
		page.setTotalCount(count);
		return page;
	}
	public LoanOrder getLoanOrderDetail(Long id) {
		
		return loanOrderMapper.getLoanOrderDetail(id);
	}
	
}
